package com.netease.nertc.demo;


import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;

import android.os.Build;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;

import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.netease.cloud.nos.android.core.CallRet;
import com.netease.cloud.nos.android.exception.InvalidChunkSizeException;
import com.netease.vcloudnosupload.AcceleratorConfig;
import com.netease.vcloudnosupload.NOSUpload;
import com.netease.vcloudnosupload.NOSUploadHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends AppCompatActivity {

    private static final boolean DEBUG = true;
    private int PICKFILE_REQUEST_CODE = 7;
    private Button btnSelectFile;
    private Button btnInit;
    private Button btn_http_upload;
    private Button btn_upload_cancel;
    private TextView txtNetUrl;
    private String mSelectedFile;
    private EditText mEditText;
    private NOSUpload nosUpload = NOSUpload.getInstace(MainActivity.this);
    private NOSUpload.UploadExecutor executor = null;
    private String mNosToken, mBucket, mObject;
    private ProgressBar progressBar;
    private Button btn_query;
    private ArrayList<String> objectList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10008);
        }
        initViews();
        if (nosUpload != null) {
            /** 这里的accid,token需要用户根据文档 http://dev.netease.im/docs/product/%E7%82%B9%E6%92%AD/%E7%A7%BB%E5%8A%A8%E7%AB%AF%E4%B8%8A%E4%BC%A0%E6%94%AF%E6%8C%81%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E
             中的/app/vod/thirdpart/user/create 接口创建 **/
            NOSUpload.Config config = new NOSUpload.Config();
            config.appKey = "";
            config.accid = "";
            config.token = "";
            nosUpload.setConfig(config);
        }

    }

    private static class HandleMsg {
        public static final int MSG_INIT_SUCCESS = 0;
        public static final int MSG_INIT_FAIL = 1;
        public static final int MSG_QUERYVIDEO_SUCCESS = 2;
        public static final int MSG_QUERYVIDEO_FAIL = 3;
    }
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case HandleMsg.MSG_INIT_SUCCESS: {
                    Toast.makeText(MainActivity.this, "init success", Toast.LENGTH_SHORT).show();
                    break;
                }
                case HandleMsg.MSG_INIT_FAIL: {
                    int code = msg.arg1;
                    String m = (String) msg.obj;
                    Toast.makeText(MainActivity.this, "init fail, code: " + code + ", msg: " + m, Toast.LENGTH_SHORT).show();
                    break;
                }
                case HandleMsg.MSG_QUERYVIDEO_SUCCESS: {
                    List<NOSUploadHandler.VideoQueryCallback.QueryResItem> list = (List< NOSUploadHandler.VideoQueryCallback.QueryResItem> ) msg.obj;
                    Toast.makeText(MainActivity.this, "query video success: " + list.toString(), Toast.LENGTH_SHORT).show();
                    break;
                }
                case HandleMsg.MSG_QUERYVIDEO_FAIL: {
                    int code = msg.arg1;
                    String m = (String) msg.obj;
                    Toast.makeText(MainActivity.this, "query video fail, code: " + code + ", msg: " + m, Toast.LENGTH_SHORT).show();
                    break;
                }

                default:
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initViews() {
        btnSelectFile = findViewById(R.id.btn_sel_file);
        mEditText = findViewById(R.id.txt_selected_file);
        btnSelectFile.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("video/*"); // 设置你希望选择的文件类型
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(Intent.createChooser(intent, "Select a File"), PICKFILE_REQUEST_CODE);
        });
        btnInit = findViewById(R.id.btn_init);
        btnInit.setOnClickListener(v -> {
            uploadInit();
        });
        btn_http_upload = findViewById(R.id.btn_http_upload);
        btn_http_upload.setOnClickListener(v -> {
            httpUpload();
        });
        btn_upload_cancel = findViewById(R.id.btn_upload_cancel);
        btn_upload_cancel.setOnClickListener(v -> {
            httpUploadCancel();
        });
        progressBar = (ProgressBar) findViewById(R.id.progress_upload);
        progressBar.setMax(1000);
        txtNetUrl = findViewById(R.id.txtNetUrl);
        btn_query = findViewById(R.id.btn_query_id);
        btn_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nosUpload.videoQuery(objectList, new NOSUploadHandler.VideoQueryCallback() {
                    @Override
                    public void onSuccess(List<QueryResItem> list) {
                        Message msg = Message.obtain(mHandler, HandleMsg.MSG_QUERYVIDEO_SUCCESS);
                        msg.obj = list;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        Message message = Message.obtain(mHandler, HandleMsg.MSG_QUERYVIDEO_FAIL);
                        message.arg1 = code;
                        message.obj = msg;
                        mHandler.sendMessage(message);
                    }
                });
            }
        });

    }
    private void httpUploadCancel() {
        if(executor != null) {
            executor.cancel();
        }
    }
    private void httpUpload() {
        if(mSelectedFile == null){
            Toast.makeText(MainActivity.this, "please select file first!", Toast.LENGTH_SHORT).show();
        }
        Intent serviceIntent = new Intent(this, ForegroundServer.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(serviceIntent);
        } else {
            startService(serviceIntent);
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                {
                    String uploadContext = null;

                    File file = new File(mSelectedFile);
                    /**
                     *  查看一个这个文件是否已经上传过，如果上传过就取出它的uploadcontext, 传给NosUpload.putFileByHttp进行断点续传
                     *  当uploadContext是null时, 就从头开始往上传
                     */
                    String tmp = nosUpload.getUploadContext(file);
                    if (tmp != null && !tmp.equals("")) {
                        uploadContext = tmp;
                        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                        String jsonStr = preferences.getString(uploadContext, "");
                        if(jsonStr != ""){
                            JSONObject jsonObject = null;
                            try {
                                jsonObject = new JSONObject(jsonStr);
                                String bucket = jsonObject.getString("bucket");
                                String object = jsonObject.getString("object");
                                String nosToken = jsonObject.getString("nosToken");
                                mBucket = bucket;
                                mObject = object;
                                mNosToken = nosToken;
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                    try {
                        AcceleratorConfig config = new AcceleratorConfig();
                        config.setChunkSize(4194304);
                        nosUpload.setAcceConfig(config);
                    } catch (InvalidChunkSizeException e) {
                        throw new RuntimeException(e);
                    }
                    try {
                        executor = nosUpload.putFileByHttps(file,
                                uploadContext, mBucket, mObject, mNosToken, new NOSUploadHandler.UploadCallback() {
                                    @Override
                                    public void onUploadContextCreate(
                                            String oldUploadContext,
                                            String newUploadContext) {
                                        /**
                                         *  将新的uploadcontext保存起来
                                         */
                                        nosUpload.setUploadContext(file, newUploadContext);

                                        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                                        SharedPreferences.Editor edit = preferences.edit();
                                        JSONObject obj = new JSONObject();
                                        try {
                                            obj.put("bucket", mBucket);
                                            obj.put("object", mObject);
                                            obj.put("nosToken", mNosToken);

                                        } catch (JSONException e) {
                                            throw new RuntimeException(e);
                                        }
                                        edit.putString(newUploadContext, obj.toString());
                                        edit.commit();
                                    }

                                    @Override
                                    public void onProcess(long current, long total) {
                                        int pro = (int) ((1.0f * current / total) * progressBar.getMax());
                                        progressBar.setProgress(pro);
                                    }

                                    @Override
                                    public void onSuccess(CallRet ret) {
                                        executor = null;
                                        /**
                                         *  清除该文件对应的uploadcontext
                                         */
                                        nosUpload.setUploadContext(file, "");
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(MainActivity.this, "upload success", Toast.LENGTH_SHORT).show();
                                            }
                                        });

                                    }

                                    @Override
                                    public void onFailure(CallRet ret) {
                                        executor = null;
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(MainActivity.this, "upload fail", Toast.LENGTH_SHORT).show();
                                                progressBar.setProgress(0);
                                            }
                                        });
                                    }

                                    @Override
                                    public void onCanceled(CallRet ret) {
                                        executor = null;
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(MainActivity.this, "upload cancel", Toast.LENGTH_SHORT).show();
                                                progressBar.setProgress(0);
                                            }
                                        });
                                    }
                                });
                        executor.join();
                    } catch (Exception ex) {
                    }

                }
            }
        }).start();
    }
    private void uploadInit() {
        if(mSelectedFile == null){
            Toast.makeText(MainActivity.this, "please select file first!", Toast.LENGTH_SHORT).show();
            return;
        }

        File file = new File(mSelectedFile);

        if (!file.exists()) {
            Log.w("AsyncPutImage", "FileNotExist");
            return;
        }
        String name = file.getName();

        nosUpload.fileUploadInit(name + ".mp4", null, -1, -1, null, null, -1, null, new NOSUploadHandler.UploadInitCallback() {
            @Override
            public void onSuccess(String nosToken, String bucket, String object) {
                mNosToken = nosToken;
                mBucket = bucket;
                mObject = object;
                Message msg = Message.obtain(mHandler, HandleMsg.MSG_INIT_SUCCESS);
                mHandler.sendMessage(msg);
                objectList.add(mObject);
            }

            @Override
            public void onFail(int code, String msg) {
                Message m = Message.obtain(mHandler, HandleMsg.MSG_INIT_FAIL);
                m.arg1 = code;
                m.obj = msg;
                mHandler.sendMessage(m);
            }
        });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICKFILE_REQUEST_CODE && resultCode == RESULT_OK) {
            String path = FileUtil.getPath(MainActivity.this, data.getData());
            mSelectedFile = path;
            mEditText.setText(mSelectedFile);
        }

    }
    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected  void onPause() {
        super.onPause();

    }

}